import { useState } from 'react'
import './ListsAndKeys.css'

// 基本列表渲染
function BasicListExample() {
  const [fruits, setFruits] = useState([
    '苹果', '香蕉', '橙子', '葡萄', '草莓'
  ])

  const addFruit = () => {
    const newFruit = prompt('添加新水果:')
    if (newFruit && newFruit.trim()) {
      setFruits([...fruits, newFruit.trim()])
    }
  }

  const removeFruit = (index) => {
    setFruits(fruits.filter((_, i) => i !== index))
  }

  return (
    <div className="example-container">
      <h4>基本列表渲染</h4>
      
      <div className="controls">
        <button onClick={addFruit}>添加水果</button>
      </div>

      <ul className="fruit-list">
        {fruits.map((fruit, index) => (
          <li key={index} className="fruit-item">
            <span>{fruit}</span>
            <button 
              onClick={() => removeFruit(index)}
              className="remove-btn"
            >
              删除
            </button>
          </li>
        ))}
      </ul>
    </div>
  )
}

// Keys 的重要性示例
function KeysExample() {
  const [users, setUsers] = useState([
    { id: 1, name: '张三', email: 'zhangsan@example.com' },
    { id: 2, name: '李四', email: 'lisi@example.com' },
    { id: 3, name: '王五', email: 'wangwu@example.com' }
  ])

  const [newUserName, setNewUserName] = useState('')
  const [newUserEmail, setNewUserEmail] = useState('')

  const addUser = () => {
    if (newUserName.trim() && newUserEmail.trim()) {
      const newUser = {
        id: Date.now(), // 使用时间戳作为临时ID
        name: newUserName.trim(),
        email: newUserEmail.trim()
      }
      setUsers([...users, newUser])
      setNewUserName('')
      setNewUserEmail('')
    }
  }

  const removeUser = (userId) => {
    setUsers(users.filter(user => user.id !== userId))
  }

  const updateUser = (userId, newName) => {
    setUsers(users.map(user => 
      user.id === userId 
        ? { ...user, name: newName }
        : user
    ))
  }

  return (
    <div className="example-container">
      <h4>Keys 的重要性</h4>
      <p className="description">
        Keys 帮助 React 识别哪些元素发生了变化，提高渲染性能。
        使用稳定的、唯一的标识符作为 key。
      </p>
      
      <div className="add-user-form">
        <input
          type="text"
          placeholder="姓名"
          value={newUserName}
          onChange={(e) => setNewUserName(e.target.value)}
        />
        <input
          type="email"
          placeholder="邮箱"
          value={newUserEmail}
          onChange={(e) => setNewUserEmail(e.target.value)}
        />
        <button onClick={addUser}>添加用户</button>
      </div>

      <div className="user-list">
        <h5>用户列表 (使用 ID 作为 key):</h5>
        <ul>
          {users.map(user => (
            <li key={user.id} className="user-item">
              <div className="user-info">
                <strong>{user.name}</strong>
                <span>{user.email}</span>
              </div>
              <div className="user-actions">
                <button onClick={() => updateUser(user.id, `${user.name} (已更新)`)}>
                  更新
                </button>
                <button onClick={() => removeUser(user.id)} className="danger">
                  删除
                </button>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}

// 错误的 Keys 使用示例
function BadKeysExample() {
  const [items, setItems] = useState([
    { text: '项目 A', priority: 'high' },
    { text: '项目 B', priority: 'medium' },
    { text: '项目 C', priority: 'low' }
  ])

  const shuffleItems = () => {
    // 随机打乱数组顺序
    const shuffled = [...items].sort(() => Math.random() - 0.5)
    setItems(shuffled)
  }

  const addItem = () => {
    const newItem = {
      text: `项目 ${items.length + 1}`,
      priority: ['high', 'medium', 'low'][Math.floor(Math.random() * 3)]
    }
    setItems([...items, newItem])
  }

  return (
    <div className="example-container">
      <h4>错误的 Keys 使用示例</h4>
      <p className="description warning">
        使用数组索引作为 key 会导致问题，特别是在列表重新排序时。
      </p>
      
      <div className="controls">
        <button onClick={shuffleItems}>随机排序</button>
        <button onClick={addItem}>添加项目</button>
      </div>

      <div className="bad-list">
        <h5>使用索引作为 key (不推荐):</h5>
        <ul>
          {items.map((item, index) => (
            <li key={index} className="bad-item">
              <span className="priority">{item.priority}</span>
              <span>{item.text}</span>
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}

// 动态列表操作
function DynamicListExample() {
  const [tasks, setTasks] = useState([
    { id: 1, text: '学习 React', completed: false },
    { id: 2, text: '完成项目', completed: true },
    { id: 3, text: '写文档', completed: false }
  ])

  const [newTask, setNewTask] = useState('')
  const [filter, setFilter] = useState('all')

  const addTask = () => {
    if (newTask.trim()) {
      const task = {
        id: Date.now(),
        text: newTask.trim(),
        completed: false
      }
      setTasks([...tasks, task])
      setNewTask('')
    }
  }

  const toggleTask = (taskId) => {
    setTasks(tasks.map(task =>
      task.id === taskId
        ? { ...task, completed: !task.completed }
        : task
    ))
  }

  const deleteTask = (taskId) => {
    setTasks(tasks.filter(task => task.id !== taskId))
  }

  const filteredTasks = tasks.filter(task => {
    if (filter === 'completed') return task.completed
    if (filter === 'active') return !task.completed
    return true
  })

  const stats = {
    total: tasks.length,
    completed: tasks.filter(t => t.completed).length,
    active: tasks.filter(t => !t.completed).length
  }

  return (
    <div className="example-container">
      <h4>动态列表操作</h4>
      
      <div className="task-stats">
        <div className="stat">
          <span className="stat-number">{stats.total}</span>
          <span className="stat-label">总计</span>
        </div>
        <div className="stat">
          <span className="stat-number">{stats.active}</span>
          <span className="stat-label">进行中</span>
        </div>
        <div className="stat">
          <span className="stat-number">{stats.completed}</span>
          <span className="stat-label">已完成</span>
        </div>
      </div>

      <div className="task-controls">
        <input
          type="text"
          placeholder="添加新任务..."
          value={newTask}
          onChange={(e) => setNewTask(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && addTask()}
        />
        <button onClick={addTask}>添加</button>
      </div>

      <div className="filter-buttons">
        <button 
          className={filter === 'all' ? 'active' : ''}
          onClick={() => setFilter('all')}
        >
          全部 ({stats.total})
        </button>
        <button 
          className={filter === 'active' ? 'active' : ''}
          onClick={() => setFilter('active')}
        >
          进行中 ({stats.active})
        </button>
        <button 
          className={filter === 'completed' ? 'active' : ''}
          onClick={() => setFilter('completed')}
        >
          已完成 ({stats.completed})
        </button>
      </div>

      <ul className="task-list">
        {filteredTasks.map(task => (
          <li 
            key={task.id} 
            className={`task-item ${task.completed ? 'completed' : 'active'}`}
          >
            <input
              type="checkbox"
              checked={task.completed}
              onChange={() => toggleTask(task.id)}
            />
            <span 
              className={`task-text ${task.completed ? 'completed-text' : ''}`}
              onClick={() => toggleTask(task.id)}
            >
              {task.text}
            </span>
            <button 
              onClick={() => deleteTask(task.id)}
              className="delete-btn"
            >
              删除
            </button>
          </li>
        ))}
      </ul>
    </div>
  )
}

// 嵌套列表渲染
function NestedListExample() {
  const [departments, setDepartments] = useState([
    {
      id: 1,
      name: '技术部',
      employees: [
        { id: 11, name: '张三', position: '前端工程师' },
        { id: 12, name: '李四', position: '后端工程师' },
        { id: 13, name: '王五', position: '技术经理' }
      ]
    },
    {
      id: 2,
      name: '产品部',
      employees: [
        { id: 21, name: '赵六', position: '产品经理' },
        { id: 22, name: '钱七', position: 'UI设计师' }
      ]
    },
    {
      id: 3,
      name: '市场部',
      employees: [
        { id: 31, name: '孙八', position: '市场总监' },
        { id: 32, name: '周九', position: '市场专员' }
      ]
    }
  ])

  const [expandedDepts, setExpandedDepts] = useState([])

  const toggleDepartment = (deptId) => {
    setExpandedDepts(prev =>
      prev.includes(deptId)
        ? prev.filter(id => id !== deptId)
        : [...prev, deptId]
    )
  }

  const removeEmployee = (deptId, empId) => {
    setDepartments(departments.map(dept =>
      dept.id === deptId
        ? {
            ...dept,
            employees: dept.employees.filter(emp => emp.id !== empId)
          }
        : dept
    ))
  }

  return (
    <div className="example-container">
      <h4>嵌套列表渲染</h4>
      
      <div className="department-list">
        {departments.map(department => (
          <div key={department.id} className="department">
            <div 
              className="department-header"
              onClick={() => toggleDepartment(department.id)}
            >
              <h5>{department.name}</h5>
              <span className="employee-count">
                ({department.employees.length} 人)
              </span>
              <span className="expand-icon">
                {expandedDepts.includes(department.id) ? '▼' : '▶'}
              </span>
            </div>
            
            {expandedDepts.includes(department.id) && (
              <ul className="employee-list">
                {department.employees.map(employee => (
                  <li key={employee.id} className="employee-item">
                    <div className="employee-info">
                      <strong>{employee.name}</strong>
                      <span>{employee.position}</span>
                    </div>
                    <button 
                      onClick={() => removeEmployee(department.id, employee.id)}
                      className="remove-employee-btn"
                    >
                      移除
                    </button>
                  </li>
                ))}
              </ul>
            )}
          </div>
        ))}
      </div>
    </div>
  )
}

function ListsAndKeys() {
  return (
    <div className="example-page">
      <div className="example-header">
        <h1>列表与 Keys</h1>
        <p>学习 React 中的列表渲染和 Keys 的正确使用方法</p>
      </div>

      <div className="example-section">
        <h2>1. 基本列表渲染</h2>
        <p>使用 map() 方法渲染数组数据：</p>
        
        <div className="code-block">
{`const fruits = ['苹果', '香蕉', '橙子']

function FruitList() {
  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li>
      ))}
    </ul>
  )
}`}
        </div>

        <BasicListExample />
      </div>

      <div className="example-section">
        <h2>2. Keys 的重要性</h2>
        <p>Keys 帮助 React 识别元素变化，提高性能：</p>
        
        <div className="code-block">
{`// 好的做法：使用稳定的 ID
{users.map(user => (
  <li key={user.id}>
    {user.name}
  </li>
))}

// 不好的做法：使用数组索引
{items.map((item, index) => (
  <li key={index}>
    {item.text}
  </li>
))}`}
        </div>

        <KeysExample />
      </div>

      <div className="example-section">
        <h2>3. 错误的 Keys 使用</h2>
        <p>展示使用索引作为 key 的问题：</p>
        
        <BadKeysExample />
      </div>

      <div className="example-section">
        <h2>4. 动态列表操作</h2>
        <p>添加、删除、更新列表项：</p>
        
        <DynamicListExample />
      </div>

      <div className="example-section">
        <h2>5. 嵌套列表渲染</h2>
        <p>渲染多层嵌套的列表结构：</p>
        
        <NestedListExample />
      </div>

      <div className="tip">
        <strong>Keys 最佳实践：</strong>
        <ul>
          <li>Key 应该是稳定的、唯一的标识符</li>
          <li>使用数据的 ID 作为 key，而不是数组索引</li>
          <li>Key 不需要全局唯一，只需在兄弟节点中唯一</li>
          <li>避免使用随机数或索引作为 key</li>
          <li>在列表重新排序时，稳定的 key 能提高性能</li>
          <li>如果列表项没有稳定的 ID，考虑生成唯一标识符</li>
        </ul>
      </div>
    </div>
  )
}

export default ListsAndKeys